package okx

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/amir-the-h/okex"
	"github.com/amir-the-h/okex/api"
	"github.com/amir-the-h/okex/requests/rest/account"
	"github.com/amir-the-h/okex/requests/rest/market"
	"net/http"
)

type Okx struct {
	Client *api.Client
}

func NewOkx(ctx context.Context, apiKey, secretKey, passphrase string) (*Okx, error) {
	dest := okex.NormalServer // The main API server
	client, err := api.NewClient(ctx, apiKey, secretKey, passphrase, dest)
	if err != nil {
		return nil, err
	}
	return &Okx{Client: client}, nil
}

// GetTickerLastPrice 获取最新价格
func (o *Okx) GetTickerLastPrice(instId string) (lastPrice string, err error) {
	rsp, err := o.Client.Rest.Market.GetIndexTickers(market.GetIndexTickers{
		InstID: instId,
	})
	if err != nil {
		return "0", err
	}
	if len(rsp.Tickers) == 0 {
		err = errors.New("获取价格失败")
		return "0", err
	}
	lastPrice = fmt.Sprintf("%f", rsp.Tickers[0].Last)
	return
}

// CreateOrder 创建订单
func (o *Okx) CreateOrder(req *CreateOrderRequest) (rsp *CreateOrderResponse, err error) {
	rsp = &CreateOrderResponse{}
	p := "/api/v5/trade/order"
	m := okex.S2M(req)
	res, err := o.Client.Rest.Do(http.MethodPost, p, true, m)
	if err != nil {
		return
	}
	defer res.Body.Close()
	d := json.NewDecoder(res.Body)
	err = d.Decode(rsp)
	return
}

// GetPositions 获取仓位
func (o *Okx) GetPositions(instId string, posSide string) (count int64, err error) {
	req := account.GetPositions{
		InstType: okex.SwapInstrument,
	}
	res, err := o.Client.Rest.Account.GetPositions(req)
	if err != nil {
		return
	}
	for _, p := range res.Positions {
		// 过滤
		if instId != p.InstID {
			continue
		}
		if posSide != "" && okex.PositionSide(posSide) != p.PosSide {
			continue
		}
		count++
	}
	return
}
